<template>
  <div class="menu-container app-container">
    <el-row>
      <el-col :span="12">
        <el-button
          size="small"
          type="primary"
          @click="handleAddDialog"
        >新增</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="24">
      <el-col :span="4">
        <el-tree
          ref="tree"
          class="pagination-container"
          :data="menuList"
          show-checkbox
          default-expand-all
          check-on-click-node
          node-key="id"
          :default-checked-keys="checkedKeys"
          :props="defaultProps"
          @check="check"
        />
      </el-col>
      <el-col :span="20">
        <CommonTable
          class="pagination-container"
          :columns="columns"
          :data-source="tableData"
          :options="options"
          :fetch="fetchTableData"
          :pagination="pagination"
          @row-click="handleRowClick"
          @selection-change="handleSelectionChange"
        />
      </el-col>
    </el-row>
    <el-dialog
      :title="formOptions.title"
      :visible.sync="formOptions.visible"
      width="50%"
      center
      @closed="closeDialog"
    >
      <el-form ref="formRef" status-icon :rules="rules" :model="formData" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单名:" prop="title">
              <el-input v-model="formData.title" placeholder="请输入菜单名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上级ID:" prop="pid">
              <!-- <el-input v-model="formData.pid" placeholder="请输入菜单名" /> -->
              <el-cascader
                v-model="formData.pid"
                :options="cascaderOptions"
                :props="{
                  expandTrigger: 'hover',
                  value: 'id',
                  label: 'title',
                  checkStrictly: true
                }"
                clearable
                :show-all-levels="false"
                @change="cascaderChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="组件名:" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标:" prop="icon">
              <el-input v-model="formData.icon" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单路径:" prop="path">
              <el-input v-model="formData.path" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件路由:" prop="component">
              <el-input v-model="formData.component" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态:" prop="hidden">
              <!-- <el-input v-model="formData.hidden" /> -->
              <el-switch
                v-model="formData.hidden"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="显示"
                inactive-text="隐藏"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色组:" prop="roles">
              <el-select v-model="formData.roles" multiple placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.role_name"
                  :value="item.role_code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="根菜单:" prop="alwaysShow">
              <!-- <el-input v-model="formData.alwaysShow" /> -->
              <el-switch
                v-model="formData.alwaysShow"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="显示"
                inactive-text="隐藏"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重定向:" prop="redirect">
              <el-input v-model="formData.redirect" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formOptions.visible = false">取 消</el-button>
        <el-button v-if="formOptions.type === 1" type="primary" @click="_handleAdd('formRef')">新增</el-button>
        <el-button v-if="formOptions.type === 2" type="primary" @click="_handleEdit('formRef')">修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '@/components/Table'
import { getMenus, addMenu, getMenuInfo, updateMenu, deleteMenu } from '@/api/menu'
import { getRoles } from '@/api/role'
import { toTree } from '@/utils'
export default {
  name: 'Menu',
  components: {
    CommonTable
  },
  data() {
    return {
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      roleOptions: [],
      cascaderOptions: [],
      checkedKeys: [], // 已配置的菜单
      checkedMenuIds: [],
      roleId: '',
      boolChecked: false, // 用于判断是否点过菜单选项，确认是否调用过check方法
      formOptions: {
        visible: false,
        title: '',
        type: 1
      },
      columns: [
        {
          prop: 'id',
          label: '编号',
          width: 60
        },
        {
          prop: 'pid',
          label: '上级ID'
        },
        {
          prop: 'title',
          label: '菜单名'
        },
        {
          prop: 'name',
          label: '组件名',
          // render 可以根据你想要渲染的方式渲染
          // jsx 不提供 v-model 指令，若你想要使用，，推荐使用插件 babel-plugin-jsx-v-model
          // jsx https://github.com/vuejs/babel-plugin-transform-vue-jsx
          render: (row, index) => {
            return (
              <span style="'color: #ccc'" onClick={e => this.handleClick(e, row)}>
                {row.name}
              </span>
            )
          }
        },
        {
          prop: 'path',
          label: '菜单路径'
        },
        {
          prop: 'component',
          label: '组件路由'
        },
        {
          prop: 'roles',
          label: '角色组'
        },
        {
          prop: 'redirect',
          label: '重定向'
        },
        {
          prop: 'alwaysShow',
          label: '是/否显示根菜单',
          render: (row, index) => {
            return (
              // <span style="'color: #621'" onClick={e => this.handleClick(e, row)}>
              //   {row.hidden}
              // </span>
              <el-tag type="'info'"> {row.alwaysShow === 1 ? '启用' : '隐藏'}</el-tag>
              // <i :class="row.meta.icon"></i>
            )
          }
        },
        {
          prop: 'icon',
          label: '菜单图标',
          render: (row, index) => {
            return (
              <span style="'color: #ccc'" onClick={e => this.handleClick(e, row)}>
                {row.meta.icon}
              </span>
              // <i :class="row.meta.icon"></i>
            )
          }
        },
        {
          prop: 'hidden',
          label: '状态',
          render: (row, index) => {
            return (
              // <span style="'color: #621'" onClick={e => this.handleClick(e, row)}>
              //   {row.hidden}
              // </span>
              <el-tag type="'success'"> {row.hidden === 1 ? '隐藏' : '启用'}</el-tag>
              // <i :class="row.meta.icon"></i>
            )
          }
        },
        {
          prop: 'created_at',
          label: '创建时间'
        },
        {
          button: true,
          label: '操作',
          group: [
            {
              // you can props => type size icon disabled plain
              name: '',
              type: 'warning',
              icon: 'el-icon-edit',
              round: true,
              plain: true,
              onClick: (row, index) => {
                // 箭头函数写法的 this 代表 Vue 实例
                this.handleEditDialog(row, index)
              }
            },
            {
              name: '',
              type: 'danger',
              icon: 'el-icon-delete',
              round: true,
              disabled: false,
              onClick: (row) => {
                // 这种写法的 this 代表 group 里的对象
                this._handleDel(row)
                this.disabled = true
              }
            }
          ]
        }
      ],
      tableData: [],
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 15
      },
      options: {
        mutiSelect: true,
        index: true, // 显示序号， 多选则 mutiSelect
        loading: true, // 表格动画
        initTable: true, // 是否一挂载就加载数据
        border: true
      },
      rules: {
        title: [
          { required: true, message: '请输入菜单名', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入组件名称', trigger: 'blur' }
        ]
      },
      formData: {
        name: '',
        pid: null,
        path: '',
        component: '',
        hidden: 0,
        roles: '',
        redirect: '',
        alwaysShow: 0,
        title: '',
        icon: ''
      },
      roleArr: []
    }
  },
  mounted() {
  },
  methods: {
    handleClick(e, row) {
      // transform-vue-jsx 的nativeOnClick 失效 , 所以采用 event.cancelBubble 控制点击事件的冒泡... 如果点击事件不影响你的点击行事件，可以不传
      e.cancelBubble = true // 停止冒泡，否则会触发 row-click
      // console.log(row)
    },
    async getRolesInfo() {
      const { pageIndex, pageSize } = this.pagination
      const res = await getRoles({ pageIndex, pageSize })
      if (res) {
        const list = res.data.data.rows
        this.roleOptions = list
      }
    },
    fetchTableData() {
      this.options.loading = true
      getMenus({
        pageIndex: this.pagination.pageIndex,
        pageSize: this.pagination.pageSize
      })
        .then(res => {
          const { rows, count } = res.data.data
          this.tableData = rows
          this.menuList = toTree(rows)
          this.cascaderOptions = toTree(rows)
          // this.cascaderOptions.push({ id: 0, title: '顶级栏目' })
          this.pagination.total = count
          this.options.loading = false
        })
        .catch(error => {
          console.log(error)
          this.options.loading = false
        })
    },
    handleRowClick(row, event, column) {
      // 点击行的事件，同理可以绑定其他事件
      // console.log('click row:', row, event, column)
    },
    handleSelectionChange(selection) {
      // console.log(selection)
    },
    handleAddDialog() {
      this.resetForm('formData')
      this.formOptions.visible = true
      this.formOptions.title = '新增菜单'
      this.formOptions.type = 1
      this.formData = {}
      this.getRolesInfo()
    },
    async handleEditDialog(row, index) {
      this.resetForm('formData')
      this.formOptions.visible = true
      this.formOptions.title = '修改菜单信息'
      this.formOptions.type = 2
      this.formData = {}
      // Object.assign(this.cascaderOptions, { id: 0, title: '顶级栏目' })
      // this.cascaderOptions.push({ id: 0, title: '顶级栏目' })
      // console.log(this.cascaderOptions)
      this.getRolesInfo()
      const res = await getMenuInfo({ id: row.menu_id })
      if (res.data) {
        const list = res.data.data
        list.roles = list.roles ? list.roles.split(',') : list.roles
        this.formData = list
      }
    },
    _handleDel(row) {
      this.$confirm(`此操作将永久删除${row.name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteMenu({ id: row.menu_id })
        if (res) {
          this.$message({
            type: 'success',
            message: res.data.message
          })
          this.fetchTableData()
        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    _handleAdd(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // const roles = this.formData.roles.toString()
          // console.log(this.formData.roles)
          Object.assign(this.formData, { roles: this.formData.roles.toString() })
          const res = await addMenu(this.formData)
          if (res.data) {
            this.$message.success(res.data.message)
            this.formOptions.visible = false
            this.fetchTableData()
          } else {
            this.$message.error(res.data.message)
          }
        } else {
          return false
        }
      })
    },
    _handleEdit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          Object.assign(this.formData, { roles: this.formData.roles.toString() })
          const res = await updateMenu(this.formData)
          console.log(res)
          if (res.data) {
            this.$message.success(res.data.message)
            this.formOptions.visible = false
            this.fetchTableData()
          } else {
            this.$message.error(res.data.message)
          }
        } else {
          return false
        }
      })
    },
    closeDialog() {
      this.formData = {}
      this.roleArr = []
      // const newarr = this.cascaderOptions.concat()
      // newarr.pop()
      // this.cascaderOptions = newarr
    },
    resetForm(formName) {
      // console.log(formName);
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    check(menuData, checkedData) {
      this.boolChecked = true
      this.checkedMenuIds = checkedData.checkedKeys.concat(
        checkedData.halfCheckedKeys
      )
    },
    handleRuleDialog(row) {
      console.log(row)
      this.dialogRoleVisible = !this.dialogRoleVisible
    },
    saveRoleMenu() {
      console.log(this.boolChecked)
      console.log(this.checkedMenuIds)
      if (!this.boolChecked) {
        this.dialogRoleVisible = false
        return
      }
      const param = {
        menuIds: this.checkedMenuIds.join(','),
        roleId: this.roleId
      }
      console.log(param)
      this.$message({
        type: 'success',
        message: '保存成功!'
      })
      this.roleId = ''
      this.checkedMenuIds = []
      this.dialogRoleVisible = false
    },
    handleNodeClick(data) {
      console.log(data)
    },
    handleCheckChange(data) {
      // console.log(data);
    },
    onChange(e) {},
    cascaderChange(e) {
      if (e) {
        if (e.length > 1) {
          this.formData.pid = e[e.length - 1]
          console.log(this.formData.pid)
        } else {
          this.formData.pid = e[0]
        }
        // e = []
      }
    }
  }
}
</script>
